package cn.jetpiece.cloud.joss.app.modular.accessor.context;

import cn.jetpiece.cloud.joss.api.constant.AccessorCache;

/**
 * 缓存请求accessor信息
 * <p>
 * 说明：
 * 当OPEN_UP_FLAG标识在ThreadLocal里为true
 *
 * @author XuJZ
 * @since 2020/12/15
 */
public class AccessorContextHolder {
    private static final ThreadLocal<Boolean> OPEN_UP_FLAG = new ThreadLocal<>();
    private static final ThreadLocal<AccessorCache> LONGIN_USER_HOLDER = new ThreadLocal<>();

    /**
     * 初始化
     */
    public static void init() {
        OPEN_UP_FLAG.set(true);
    }

    /**
     * 这个方法如果OPEN_UP_FLAG标识没开启，则会set失效
     */
    public static void set(AccessorCache cache) {
        Boolean openUpFlag = OPEN_UP_FLAG.get();
        if (openUpFlag != null && openUpFlag.equals(false)) {
            LONGIN_USER_HOLDER.set(cache);
        }
    }

    /**
     * 这个方法如果OPEN_UP_FLAG标识没开启，则会get值为null
     */
    public static AccessorCache get() {
        Boolean openUpFlag = OPEN_UP_FLAG.get();
        if (openUpFlag == null || openUpFlag.equals(false)) {
            return null;
        } else {
            return LONGIN_USER_HOLDER.get();
        }
    }

    /**
     * 删除保存的信息
     */
    public static void remove() {
        OPEN_UP_FLAG.remove();
        LONGIN_USER_HOLDER.remove();
    }
}
